<?php
namespace App\GraphQL\Mutations\Group;

use App\Models\AgentStatistical;
use App\Models\Device;
use App\Models\DistributorStatistical;
use App\Models\Group;
use App\Models\MerchantStatistical;
use GraphQL\Type\Definition\ResolveInfo;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use Nuwave\Lighthouse\Support\Contracts\GraphQLContext;
use App\Models\DeviceOrder;

class AddDevice
{

    /**
     * Return a value for the field.
     *
     * @param null $rootValue
     *            Usually contains the result returned from the parent field. In this case, it is always `null`.
     * @param mixed[] $args
     *            The arguments that were passed into the field.
     * @param \Nuwave\Lighthouse\Support\Contracts\GraphQLContext $context
     *            Arbitrary data that is shared between all fields of a single query.
     * @param \GraphQL\Type\Definition\ResolveInfo $resolveInfo
     *            Information about the query itself, such as the execution state, the field name, path to the field from the root, and more.
     * @return mixed
     */
    public function __invoke($rootValue, array $args, GraphQLContext $context, ResolveInfo $resolveInfo)
    {
        DB::transaction(function () use ($args) {
            $data = $args['input'];
            $id = $args['id'];
            $device = $this->validate($id, $data);
            $device->device_group_id = $id;
            $device->device_order_id = $data['device_order_id'];
            $group = Group::find($data['device_group_id']);
            // 增加新的
            $agentStatistical = AgentStatistical::firstOrCreate([
                'user_id' => $group->user_id
            ]);
            $agentStatistical->increment('link_device_count');
            // 更新终端伙伴设备统计
            if ($group->merchant) {
                $merchantStatistical = MerchantStatistical::firstOrCreate([
                    'user_id' => $group->merchant->id
                ]);
                $merchantStatistical->increment('link_device_count');
            }
            // 更新分销商统计
            $distributors = $group->members()
            ->where('role', 'DISTRIBUTOR')
            ->get();
            $distributors->map(function ($distributor) {
                $distributorStatistical = DistributorStatistical::firstOrCreate([
                    'user_id' => $distributor->user_id
                ]);
                $distributorStatistical->increment('link_device_count');
            });
        });
        return [
            'status' => '200',
            'message' => '创建成功'
        ];
    }

    public function validate($id, $data)
    {
        $rules = [
            'device_id' => [
                'nullable',
                'numeric'
            ],
            'device_order_id' => [
                'nullable',
                'numeric'
            ],
        ];
        if ($data['cate'] == 'STAFF') {
            $rules['device_group_id'] = [
                'required',
                'integer'
            ];
        }
        $messages = [
            'device_id.required' => '名称不能为空',
            'device_order_id.required' => '设备订单不能为空',
            'device_id.numeric' => '设备不正确',
            'device_order_id.numeric' => '设备订单不正确',
        ];
        $validate = Validator::make($data, $rules, $messages);
        if ($validate->fails()) {
            throw new \InvalidArgumentException($validate->messages()->first());
        }
        $device = Device::find($data['device_id']);
        if (! $device) {
            throw new \Exception('设备不存在');
        }
        $group = Group::find($id);
        if (! $group) {
            throw new \Exception('群组不存在');
        }
        if ($group->cate == 'STAFF') {
            throw new \Exception('分润员工群组不能添加设备');
        }
        $deviceOrder = DeviceOrder::find($data['device_order_id']);
        if (! $deviceOrder) {
            throw new \Exception('设备订单不存在');
        }
        return true;
    }
}
